package com.boot.webflux.security.example2.config.authentication;

import com.boot.webflux.security.example2.config.CloudUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 认证管理器: 校验用户名密码是否正确
 *
 */
@Component
@Slf4j
public class CloudAuthenticationManager  implements ReactiveAuthenticationManager {
    @Autowired
    private CloudUserDetailsService cloudUserDetailsService;

    /**
     * 开发人员实现对 Authentication 的校验逻辑。
     * @param authentication
     * @return
     */
    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        log.info("------访问 AuthenticationManager  。。。。。。。。。。。"+authentication);
        String username = (String)authentication.getPrincipal();
        String password = (String)authentication.getPrincipal();
        UserDetails user = cloudUserDetailsService.findByUsername(username).block();
        Authentication auth = new UsernamePasswordAuthenticationToken(user,password,user.getAuthorities());
        return Mono.just(auth);
    }
}
